import { apiRequest, showNotification } from './utils.js';

// 用户管理模块
export class UserModule {
  constructor() {
    this.users = [];
    this.newUser = {
      id: null,
      name: '',
      email: ''
    };
    this.editingUser = null;
  }

  // 加载用户列表
  async loadUsers() {
    try {
      this.users = await apiRequest('/api/users');
      return this.users;
    } catch (error) {
      console.error('加载用户数据失败:', error);
      throw error;
    }
  }

  // 创建或更新用户
  async saveUser(userData) {
    try {
      let result;
      if (userData.id) {
        // 更新用户
        result = await apiRequest(`/api/users/${userData.id}`, {
          method: 'PUT',
          body: JSON.stringify(userData)
        });
        // 更新本地列表
        const index = this.users.findIndex(u => u.id === result.id);
        if (index !== -1) {
          this.users[index] = result;
        }
        showNotification('用户更新成功', 'success');
      } else {
        // 创建新用户
        result = await apiRequest('/api/users', {
          method: 'POST',
          body: JSON.stringify(userData)
        });
        this.users.push(result);
        showNotification('用户添加成功', 'success');
      }
      return result;
    } catch (error) {
      console.error('保存用户失败:', error);
      throw error;
    }
  }

  // 删除用户
  async deleteUser(userId) {
    try {
      await apiRequest(`/api/users/${userId}`, {
        method: 'DELETE'
      });
      // 从本地列表中移除
      this.users = this.users.filter(u => u.id !== userId);
      showNotification('用户删除成功', 'success');
      return true;
    } catch (error) {
      console.error('删除用户失败:', error);
      throw error;
    }
  }

  // 设置编辑用户
  setEditingUser(user) {
    this.editingUser = user;
    if (user) {
      this.newUser = { ...user };
    } else {
      this.newUser = {
        id: null,
        name: '',
        email: ''
      };
    }
  }

  // 获取过滤后的用户列表
  getFilteredUsers(searchTerm = '') {
    if (!searchTerm) {
      return this.users;
    }
    const search = searchTerm.toLowerCase();
    return this.users.filter(user => 
      user.name.toLowerCase().includes(search) || 
      user.email.toLowerCase().includes(search)
    );
  }
}